package com.gemme.gemme.wode;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.R;
import com.gemme.gemme.fragment.BaseLazyFragment;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.view.DefineLoadMoreView;
import com.gemme.gemme.view.GuanzhuHeadView;
import com.gemme.gemme.view.GuanzhuItem9View;
import com.gemme.gemme.view.GuanzhuSingleItemView;
import com.gemme.gemme.view.RefreshView;
import com.gemme.gemme.view.SingleShouruView;
import com.gemme.gemme.view.SingleTxianView;
import com.gemme.gemme.view.StaggeredDividerItemDecoration;
import com.yanzhenjie.recyclerview.OnItemClickListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;


/**
 * Created by sp on 2019/7/18.
 * 首页
 */
public class PlatFormTixianFragment extends BaseLazyFragment  {

    View inflate;
    Context mContext;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        inflate = inflater.inflate(R.layout.fragment_tixian, container, false);

        mContext = PlatFormTixianFragment.this.getContext();

        initView(inflate);

        return inflate;
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();

    }
    List<TixianBean.DataBean.RecordsBean> records = new ArrayList<>();
    TiXianAdapter tiXianAdapter;
    private void getData() {
//        http://192.168.1.6:9999/user/capital/coinrecord?current=1&size=10&type=1
        String url = DataManager.BaseUrl +
                ":9999/user/capital/coinrecord?" +
                "current=" + refreshBean.getPageIndex() +
                "&size=" + "1000" +
                "&type=2" ;

        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(getContext()));
        DataManager.toServer3(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try {
                    TixianBean tixianBean = JSON.parseObject(response, TixianBean.class);
                    List<TixianBean.DataBean.RecordsBean> serverList = tixianBean.getData().getRecords();
                    if(serverList == null)
                        return;
                    if(refreshBean.isRefresh()){
                        records.clear();
                        records.addAll(serverList);
                    } else{
                        records.addAll(serverList);
                    }
//                    refreshview.setRefreshing(false);
//                    refreshview.loadMoreFinish(false, true);



                    System.out.println("");
                    LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> hashmap = detailData(records);

                    //设置适配器
                   if(refreshBean.isRefresh()){
                       tiXianAdapter = new TiXianAdapter(hashmap);
                       refreshview.setAdapter(tiXianAdapter);
                   }else{
                       refreshview.setAdapter(tiXianAdapter);
                       tiXianAdapter.setData(hashmap);
                       tiXianAdapter.notifyDataSetChanged();
//                       tiXianAdapter.notifyItemRangeChanged(records.size() - serverList.size(),serverList.size());
                   }


                }catch (Exception e){

                }
            }
        });
    }

    private LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> detailData(List<TixianBean.DataBean.RecordsBean> records) {
        LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> hashMap = new LinkedHashMap<>();
        try {
            for (int i = 0; i < records.size(); i++) {
                TixianBean.DataBean.RecordsBean bean = records.get(i);
                String createTime = bean.getCreateTime();
                if(!TextUtils.isEmpty(createTime) && createTime.length() >= 10){
                    createTime = createTime.substring(0,10);
                }
                ArrayList<TixianBean.DataBean.RecordsBean> childList;
                if(!hashMap.containsKey(createTime)){//不包含,新建
                    childList = new ArrayList<>();
                    childList.add(bean);
                    hashMap.put(createTime,childList);
                }else{//包含,取出来添加
                    childList = hashMap.get(createTime);
                    childList.add(bean);
                }

            }
        }catch (Exception e){

        }
        return hashMap;
    }



    private void initView(View inflate) {
        initRefresh(inflate);
    }

    RefreshView refreshview;
    private void initRefresh(View inflate) {
        refreshview = inflate.findViewById(R.id.refreshview);
        //设置布局管理器
        refreshview.setLayoutManager(new LinearLayoutManager(mContext));
        refreshview.loadMoreFinish(false, false);
        controlRefresh();

    }
    RefreshView.RefreshBean refreshBean;
    private void controlRefresh() {
        refreshBean = new RefreshView.RefreshBean();
        refreshBean.setPageIndex(1);
        refreshBean.setPageSize(10);
        refreshview.setGMOnFreshListener(new RefreshView.GMOnFreshListener() {
            @Override
            public void onRefresh() {
                System.out.println();
                //下拉更多  数据索引为初始状态1
                refreshBean.setPageIndex(1);
                refreshBean.setRefresh(true);
                getData();
            }

            @Override
            public void onLoadMore() {
                System.out.println();
                //加载更多  数据索引加1
                refreshBean.setPageIndex(refreshBean.getPageIndex() + 1);
                refreshBean.setRefresh(false);
                getData();
            }
        });
    }


    @Override
    public void onLazyLoad() {

        //yc

//        getData();
    }



    public class TiXianAdapter extends RecyclerView.Adapter<TiXianAdapter.ViewHolder>{

        private LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> hashmap;

        public TiXianAdapter(LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> hashmap) {

            this.hashmap = hashmap;
        }
        public void setData(LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> hashmap) {
            this.hashmap = hashmap;
        }

        @NonNull
        @Override
        public TiXianAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View inflate = LayoutInflater.from(parent.getContext()).
                    inflate(R.layout.item_platform_tixian, null);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            inflate.setLayoutParams(layoutParams);
            return new TiXianAdapter.ViewHolder(inflate);
        }

        @Override
        public void onBindViewHolder(@NonNull TiXianAdapter.ViewHolder holder, int position) {
           /* Map.Entry<String, ArrayList<TixianBean.DataBean.RecordsBean>> dataByIndex = getDataByIndex(hashmap, position);
            holder.tv_date.setText(dataByIndex.getKey());
            ArrayList<TixianBean.DataBean.RecordsBean> value = dataByIndex.getValue();
            if(value == null)
                return;
            for (int i = 0; i < value.size(); i++) {
                TixianBean.DataBean.RecordsBean recordsBean = value.get(i);
                SingleTxianView singleTxianView = new SingleTxianView(mContext);
                singleTxianView.setData(recordsBean);
                holder.ll_content.addView(singleTxianView);
            }*/

           try {
               String key= getDataByIndex1(hashmap, position);

               holder.tv_date.setText(key);
               ArrayList<TixianBean.DataBean.RecordsBean> value = hashmap.get(key);
               if(value == null)
                   return;
               for (int i = 0; i < value.size(); i++) {
                   TixianBean.DataBean.RecordsBean recordsBean = value.get(i);
                   SingleTxianView singleTxianView = new SingleTxianView(mContext);
                   singleTxianView.setData(recordsBean);
                   holder.ll_content.addView(singleTxianView);
               }
           }catch (Exception e){

           }
        }

        public  Map.Entry<String, ArrayList<TixianBean.DataBean.RecordsBean>> getDataByIndex(LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> map,int index){
            Map.Entry<String, ArrayList<TixianBean.DataBean.RecordsBean>> next = null;
            try {
                Set<Map.Entry<String, ArrayList<TixianBean.DataBean.RecordsBean>>> entrySet = map.entrySet();
                Iterator<Map.Entry<String, ArrayList<TixianBean.DataBean.RecordsBean>>> entryit  = entrySet.iterator();
                int i = 0;
                while(entryit.hasNext()){
                    if (i == index){
                        next = entryit.next();
                        break;
                    }

                    i++;

                }
            }catch (Exception e){

            }

            return next;
        }

        public String getDataByIndex1(LinkedHashMap<String, ArrayList<TixianBean.DataBean.RecordsBean>> map,int index){

            int i = 0;
            String mapkey = "";
            for (String key : map.keySet()) {
                if(i == index){
                    mapkey = key;
                }
                System.out.println("Key = " + key);
                i ++;
            }

            return mapkey;
        }


        @Override
        public int getItemCount() {
           return hashmap.size();
        }



        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView tv_date;
            LinearLayout ll_content;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                tv_date = itemView.findViewById(R.id.tv_date);
                ll_content = itemView.findViewById(R.id.ll_content);
            }
        }
    }







}
